package com.atstudying.mall.mallcart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atstudying.common.utils.R;
import com.atstudying.common.vo.SkuInfoVo;
import com.atstudying.mall.mallcart.feign.ProductFeignService;
import com.atstudying.mall.mallcart.interceptor.CartInterceptor;
import com.atstudying.mall.mallcart.service.CartService;
import com.atstudying.mall.mallcart.vo.Cart;
import com.atstudying.mall.mallcart.vo.CartItem;
import com.atstudying.mall.mallcart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * @author Mr.zhneg
 * @create 2020-11-15-18:39
 */
@Slf4j
@Service("CartService")
public class CartServiceImpl implements CartService{

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    ProductFeignService productFeignService;

    private final String CART_PREFIX="mall:cart";

    /**
     * 添加商品到购物车
     * @param skuId
     * @param num
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String o = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(o)){
            //2：添加新商品到购物车
            CartItem cartItem=new CartItem();

            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                //2.1：远程查询当前要添加的商品信息

                R info = productFeignService.info(skuId);
//                log.error(info+"................................+++");
//                log.error("................................");

//                System.out.println(info.getCode()+"edddddddddddddddddd");


                SkuInfoVo data = info.getData("skuInfo",new TypeReference<SkuInfoVo>() {
                });
//                log.error(data+"................................");

                //2.2：商品添加到购物车
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(data.getSkuDefaultImg());


                cartItem.setTitle(data.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(data.getPrice());
//                log.error(String.valueOf(cartItem).toString());
//                System.out.println(cartItem);

            }, executor);

            CompletableFuture<Void> getskuSaleAttrValuesTask = CompletableFuture.runAsync(() -> {
                //3：远程查询sku的组合信息
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(skuSaleAttrValues);
//                log.error(String.valueOf(cartItem).toString()+".....");

            },executor);


//
//            log.error(String.valueOf(getSkuInfoTask));
//            log.error(String.valueOf(getskuSaleAttrValuesTask));

//等他们都完成才可以给redis中放数据
            //     * @throws NullPointerException if the array or any of its elements are
            CompletableFuture.allOf(getSkuInfoTask,getskuSaleAttrValuesTask).get();
            String string = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(),string);
            return cartItem;
        }else {

            //原有的商品，我们只要在增加数量即可
            CartItem cartItems=new CartItem();

            //购物出有次商品，修改数量
             cartItems = JSON.parseObject(o, CartItem.class);
             cartItems.setCount(cartItems.getCount()+num);
            String string = JSON.toJSONString(cartItems);
            cartOps.put(skuId.toString(),string);
            return cartItems;
        }

    }

    /**
     * 获取购物车中某个购物项
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String o = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(o, CartItem.class);
        return cartItem;
    }

    /**
     * 获取整个购物车
     * @return
     */
    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {

        Cart cart=new Cart();
        UserInfoTo userInfoTo=CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId()!=null){
            //1：登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(cartKey);
            //2：如果临时购物车数据还没有进行合并
            String tempCartKey=CART_PREFIX+userInfoTo.getUserKey();
            List<CartItem> tempCartItems = getCartItems(tempCartKey);
            if (tempCartItems!=null){
                //临时购物车有数据，需要合并
                for (CartItem item:tempCartItems){
                    addToCart(item.getSkuId(),item.getCount());
                }
                //清除临时购物车的数据
                clearCart(tempCartKey);

            }

            //3：获取登录后的购物车数据【包含合并过来的临时购物车数据，和登录后的购物车数据】
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);

        }else {
            //2：没登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            //获取临时购物车的所有购物项
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);

        }

        return cart;
    }

    /**
     * 获取到我们要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        String cartKey="";
        if (userInfoTo.getUserId()!=null){

            cartKey=CART_PREFIX+userInfoTo.getUserId();

        }else {
            cartKey=CART_PREFIX+userInfoTo.getUserKey();
        }

        //绑定一个hash操作（获取购物车的信息，所有的增删改查都是由这个完成
        BoundHashOperations<String, Object, Object> stringObjectObjectBoundHashOperations = stringRedisTemplate.boundHashOps(cartKey);
        return stringObjectObjectBoundHashOperations;
    }

    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(cartKey);
        //获取redis中的值
        List<Object> values = hashOps.values();

        if (values!=null&&values.size()>0){
            List<CartItem> collect = values.stream().map(obj -> {
                String str=(String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 清空购物车数据
     * @param cartkey
     */
    @Override
    public void clearCart(String cartkey){

        stringRedisTemplate.delete(cartkey);
    }

    /**
     * 勾选购物项
     * @param skuId
     * @param check
     */
    @Override
    public void checkItem(Long skuId, Integer check) {

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String string = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),cartItem);
    }

    /**
     * 修噶购物项数量
     * @param skuId
     * @param num
     */
    @Override
    public void changeItemCount(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        String string = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),cartItem);
    }

    /**
     * 删除购物项
     * @param skuId
     */
    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        if (userInfoTo.getUserId()==null){
            return null;
        }else {
            String s = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(s);
            //从redis（getCartItems(s);）里面获取所有被选中的购物项
            List<CartItem> collect = cartItems.stream().
                    filter(cartItem -> cartItem.getCheck() == true)
                    .map(item->{
                        //todo 更新为最新价格
                        R price = productFeignService.getPrice(item.getSkuId());
                        String data = (String) price.get("data");
                        item.setPrice(new BigDecimal(data));
                        return item;
                    })
                    .collect(Collectors.toList());
            return collect;

        }
    }
}
